'use strict';

const nanoid = require('nanoid');
const generatorSpanid = require('../../lib/spanid').generate;

module.exports = () => async (ctx, next) => {
  const trackId = ctx.get('yc-request-id') || nanoid();
  ctx.trackId = trackId;
  ctx.traceId = trackId;
  ctx.spanid = generatorSpanid();
  if (ctx.tracer) {
    ctx.traceId = ctx.tracer.traceId;
    ctx.trackId = ctx.tracer.traceId;
  } else {
    ctx.tracer = { traceId: trackId };
  }
  await next();
  ctx.set('yc-request-id', ctx.traceId);
};
